package logging

import (
	"fmt"
	"io"
	"log"
	"os"
	"path/filepath"
	"runtime"
	"time"
)

var (
	prefix        = ""
	levels        = []string{"DEBUG", "INFO"}
	logger        *log.Logger
	DefaultPrefix = ""
	F             *os.File
)

type Level int

const (
	DEBUG = iota
	INFO
)

func getLogFilePath() string {
	return fmt.Sprintf("%s", "logs")
}

// getLogFileName get the save name of the log file
func getLogFileName() string {
	return fmt.Sprintf("%s%s.%s",
		"log",
		time.Now().Format("20060102"),
		"log",
	)
}

func Setup() {
	filePath := getLogFilePath()
	fileName := getLogFileName()
	dir, _ := os.Getwd()
	src := dir+"\\"+filePath+"\\"+fileName
	fmt.Println("LogFile", src)

	os.MkdirAll("logs", os.ModePerm)
	F, err := os.OpenFile(src, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0644)
	if err != nil {
		fmt.Println("log err", err)
	}
	mw := io.MultiWriter(os.Stdout,F)
	logger = log.New(mw, DefaultPrefix, log.LstdFlags)
}

func Debug(v ...interface{}) {
	setPrefix(DEBUG)
	logger.Printf("%v", v)
}

func setPrefix(level Level) {
	_, file, line, ok := runtime.Caller(2)
	if ok {
		prefix = fmt.Sprintf("[%s][%s:%d]", levels[level], filepath.Base(file), line)
	} else {
		prefix = fmt.Sprintf("[%s]", levels[level])
	}
	logger.SetPrefix(prefix)
}
